import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/knowledgeword.dart';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/models/student/StudentItem.dart';
import 'package:ichinesereader/models/knowledgeword/shareKnowledgeWordsDto.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/widgets/buttons/debouncedMaterialButton.dart';
import '../../themes/appTheme.dart';

// ignore: must_be_immutable
class SelectStudentsDialog extends GetView<KnowledgeWordsController> {
  SelectStudentsDialog({
    Key? key,
    required this.title,
  }) : super(key: key);

  String title;
  final SchoolAdminController _controller = Get.find();
  List<StudentItem> _selectedStudentLists = [];
  late List<StudentItem> _allStudentLists;

  void onSelectStudent(List<StudentItem> students) {
    _selectedStudentLists = students;
  }

  void shareToSelectedStudents() {
    ShareKnowledgeWordsDto dto = ShareKnowledgeWordsDto();
    dto.shareUserIds = [];
    if (_controller.getShareAll.value) {
      for (int i = 0; i < _allStudentLists.length; i++) {
        dto.shareUserIds?.add(_allStudentLists[i].userId.toString());
      }
    } else {
      for (int i = 0; i < _selectedStudentLists.length; i++) {
        dto.shareUserIds?.add(_selectedStudentLists[i].userId.toString());
      }
    }
    dto.folderIds = controller.getSelectedFolderAWord().folderIds;
    dto.knowledgeIds = controller.getSelectedFolderAWord().knowledgeIds;
    controller.shareKnowledgeWordsToStudents(dto);
  }

  @override
  Widget build(BuildContext context) {
    final myKey = GlobalKey<DropdownSearchState<StudentItem>>();
    if (_controller.classDetailsNew.value.studentResps == null) {
      var box = Hive.box('appconfig');
      var classId = box.get(CacheManagerKey['currentclass'].toString());
      _controller.fetchClassDetailsNewByClassId(classId);
    }
    return AlertDialog(
      title: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            this.title,
            style: TextStyle(
                decoration: TextDecoration.underline,
                decorationStyle: TextDecorationStyle.dotted),
          ),
          InkWell(
            onTap: () {
              Navigator.of(context).pop();
            },
            child: Icon(Icons.cancel,
                color: Get.isDarkMode ? Colors.white : Colors.blueGrey),
          ),
        ],
      ),
      titleTextStyle: TextStyle(
          letterSpacing: 1,
          color: Get.isDarkMode ? Get.theme.primaryColorDark : Colors.blueGrey,
          fontSize: 30),
      backgroundColor:
          Get.isDarkMode ? AppTheme.colors.darkTheme2 : Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(
          Radius.circular(6.0),
        ),
      ),
      content: Container(
        height: 300.0,
        width: 450.0,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _controller.obx((data) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 12.0),
                    child: CheckboxListTile(
                      activeColor: Get.isDarkMode
                          ? Colors.white
                          : Get.theme.primaryColor,
                      checkColor: Get.isDarkMode
                          ? Colors.black
                          : Get.theme.primaryColorLight,
                      title: Text(
                        'All Students?'.tr,
                        style: TextStyle(
                            color: Get.isDarkMode
                                ? Colors.white
                                : Colors.blueGrey),
                      ),
                      value: _controller.getShareAll.value,
                      onChanged: (newValue) {
                        _allStudentLists = _controller.classDetailsNew.value
                            .studentResps as List<StudentItem>;
                        _controller.changeCheckedValue(newValue!);
                      },
                      controlAffinity: ListTileControlAffinity
                          .leading, //  <-- leading Checkbox
                    ),
                  ),
                  if (!_controller.getShareAll.value)
                    DropdownSearch<StudentItem>.multiSelection(
                      items: _controller.classDetailsNew.value.studentResps
                          as List<StudentItem>,
                      compareFn: (i1, i2) => i1.userName == i2.userName,
                      itemAsString: (item) {
                        return item.userName.toString() +
                            ' - ' +
                            item.firstName.toString() +
                            ' ' +
                            item.lastName.toString();
                      },
                      dropdownDecoratorProps: DropDownDecoratorProps(
                        dropdownSearchDecoration: InputDecoration(
                          labelText: "Choose Student",
                          labelStyle: TextStyle(
                            color: Get.isDarkMode
                                ? Get.theme.primaryColor
                                : Colors.grey[300],
                          ),
                        ),
                      ),
                      popupProps: PopupPropsMultiSelection.menu(
                          showSearchBox: true,
                          itemBuilder: (ctx, item, isSelected) {
                            return ListTile(
                              selected: isSelected,
                              title: Text(item.userName.toString()),
                            );
                          }),
                      key: myKey,
                      // selectedItems: [],
                      onChanged: onSelectStudent,
                    ),
                ],
              );
            }),
            Center(
              child: Container(
                width: 210.0,
                height: 45.0,
                child: DebouncedMaterialButton(
                  color: Get.isDarkMode
                      ? (Colors.white)
                      : Theme.of(context).primaryColor,
                  textColor: Get.isDarkMode
                      ? (Colors.black)
                      : Theme.of(context).primaryColorLight,
                  onPressed: () {
                    shareToSelectedStudents();
                    showSnackMsg('Successfully Shared');

                    Navigator.of(context).pop();
                  },
                  child: Text(
                    'Submit'.tr,
                    style: TextStyle(fontSize: 18.0),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
